package ext.acae2.dms.load;

import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import wt.content.ApplicationData;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.doc.WTDocument;
import wt.fc.PersistenceHelper;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.log4j.LogR;
import wt.util.WTException;
import wt.util.WTMessage;
import wt.util.WTPropertyVetoException;

import com.ptc.core.foundation.type.server.impl.TypeHelper;
import com.ptc.core.meta.common.TypeIdentifier;

import ext.acae2.dms.bean.DataBean;
import ext.acae2.dms.bean.DocumentBean;
import ext.acae2.dms.resource.DataExchangeResource;
import ext.acae2.util.IBAUtil;
import ext.acae2.util.QueryUtil;
import ext.acae2.util.VersionUtil;

/**
 * DocumentFacotry for create WTDocument from a bean class.
 * 
 * @author
 *
 */
public class DocumentFactory {

    private static final Logger LOGGER = LogR.getLogger(DocumentFactory.class.getName());
    private static final String RESOURCE = DataExchangeResource.class.getName();
    private static DocumentFactory factory = null;
    
    private DocumentFactory() {}
    
    /**
     * Singleton Pattern to get factory
     * 
     * @return factory
     */
    public static synchronized DocumentFactory getInstance() {
        if (factory == null) {
            factory = new DocumentFactory();
        }
        return factory;
    }
    
    /**
     * Main method to create WTDocument from a bean class.
     * 
     * @param bean class to store info 
     * @return
     * @throws WTException
     * @throws WTPropertyVetoException
     * @throws RemoteException
     */
    public WTDocument createDocument(DataBean bean) throws WTException, WTPropertyVetoException, RemoteException {
        LOGGER.debug("> Start createDocument");
        LOGGER.debug("bean class: " + bean.getClass().getName());
        
        if (bean instanceof DocumentBean) {
            return createWTDocument(bean);
        }
        
        LOGGER.debug("> End createDocument");
        return null;
    }
    
    
    /**
     * Main method to create WTDocument from a bean class.
     * 
     * @param bean
     * @return
     * @throws WTPropertyVetoException
     * @throws WTException
     * @throws RemoteException 
     */
    private WTDocument createWTDocument(DataBean bean) throws WTPropertyVetoException, WTException, RemoteException {
        LOGGER.debug("> Start createWTDocument");
        
        DocumentBean documentBean = (DocumentBean) bean;
        
        String supplier = documentBean.getSupplier();
        
        String folderName = "/Default/" + WTMessage.getLocalizedMessage(RESOURCE, DataExchangeResource.WTDOCUMENT_FOLDER_NAME) 
                + "/" + WTMessage.getLocalizedMessage(RESOURCE, "FOLDER_NAME_" + supplier);
        
        //change productName   *********************************************************
        WTDocument document = createCommonDocumentToFolder(
                "WCTYPE|wt.doc.WTDocument", documentBean.getName(), documentBean.getNumber(), "CJ-1000AX", folderName,bean.getVersion());

        String filePath = documentBean.getLocationRef();
        ApplicationData applicationdata = ApplicationData.newApplicationData(document);
        applicationdata.setRole(ContentRoleType.toContentRoleType("PRIMARY"));
        LOGGER.debug("Upload EPMPrimaryContent:" + filePath);
        if (!"".equals(filePath)) {
            try {
				ContentServerHelper.service.updateContent(document, applicationdata, filePath);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        
        IBAUtil iba = new IBAUtil(document);
        
        Set<String> key = documentBean.getMap().keySet();    
		 for (Iterator<String> it = key.iterator(); it.hasNext();) {            
			 String s = (String) it.next(); 
			 try{
				 iba.setIBAValue(s, documentBean.getMap().get(s));
			 }catch(Exception e){
				 iba.setIBAValue("remark", documentBean.getREMARK()+s+"="+documentBean.getMap().get(s)+",");
			 }
		 }
        
//        iba.setIBAValue("objName", documentBean.getOBJNAME());
//        iba.setIBAValue("title", documentBean.getTITLE());
//        iba.setIBAValue("documentID", documentBean.getDOCUMENTID());
//        iba.setIBAValue("documentType", documentBean.getDOCUMENTTYPE());
//        iba.setIBAValue("model", documentBean.getMODEL());
//        iba.setIBAValue("copyright", documentBean.getCOPYRIGHT());
//        iba.setIBAValue("design", documentBean.getDESIGN());
        iba.saveIBAHolder(document);        
        
        LOGGER.debug("> End createWTDocument");
        return document;
    }
    
    /**
     * Main method to create a common WTDocument according to type, name, number and product name.
     * 
     * @param type
     * @param name
     * @param number
     * @return
     * @throws WTException
     * @throws WTPropertyVetoException
     */
    public WTDocument createCommonDocument(String type, String name, String number, String productName) throws WTException, WTPropertyVetoException {
        LOGGER.debug("> Start createCommonDocument");
        LOGGER.debug("type: " + type);
        LOGGER.debug("name: " + name);
        LOGGER.debug("number: " + number);
        
        TypeIdentifier typeId = TypeHelper.getTypeIdentifier(type);
        WTDocument doc = (WTDocument) TypeHelper.newInstance(typeId);
        
        doc.setName(name);
        doc.setNumber(number);
        doc.setContainer(QueryUtil.getContainerByName(productName));
        
        doc = (WTDocument) PersistenceHelper.manager.save(doc);
        
        LOGGER.debug("> End createCommonDocument");
        return doc;
    }
    
    public WTDocument createCommonDocument(String type, String name, String productName) 
            throws WTException, WTPropertyVetoException {
        LOGGER.debug("> Start createCommonDocument");
        LOGGER.debug("type: " + type);
        LOGGER.debug("name: " + name);
        
        TypeIdentifier typeId = TypeHelper.getTypeIdentifier(type);
        WTDocument doc = (WTDocument) TypeHelper.newInstance(typeId);
        
        doc.setName(name);
        doc.setContainer(QueryUtil.getContainerByName(productName));
        
        doc = (WTDocument) PersistenceHelper.manager.save(doc);
        
        LOGGER.debug("> End createCommonDocument");
        return doc;
    }
    
    @SuppressWarnings("deprecation")
    public WTDocument createCommonDocumentToFolder(
            String type, String name, String productName, String folderName) 
                    throws WTException, WTPropertyVetoException {
        LOGGER.debug("> Start createCommonDocumentToFolder");
        LOGGER.debug("type: " + type);
        LOGGER.debug("name: " + name);
        LOGGER.debug("productName: " + productName);
        LOGGER.debug("folderName: " + folderName);
        
        TypeIdentifier typeId = TypeHelper.getTypeIdentifier(type);
        WTDocument doc = (WTDocument) TypeHelper.newInstance(typeId);
        
        WTContainer product = QueryUtil.getContainerByName(productName);
        
        doc.setName(name);
        doc.setContainer(product);
        
        Folder folder = QueryUtil.getFolder(folderName, WTContainerRef.newWTContainerRef(product));
        if (folder != null) {
            LOGGER.debug("folder exists!");
            FolderHelper.assignLocation(doc, folder);
        }
        
        doc = (WTDocument) PersistenceHelper.manager.save(doc);
        
        LOGGER.debug("> End createCommonDocumentToFolder");
        return doc;
    }
    
    @SuppressWarnings("deprecation")
    public WTDocument createCommonDocumentToFolder(
            String type, String name, String number, String productName, String folderName,String version) 
                    throws WTException, WTPropertyVetoException {
        LOGGER.debug("> Start createCommonDocumentToFolder");
        LOGGER.debug("type: " + type);
        LOGGER.debug("name: " + name);
        LOGGER.debug("number: " + number);
        LOGGER.debug("productName: " + productName);
        LOGGER.debug("folderName: " + folderName);
        
        TypeIdentifier typeId = TypeHelper.getTypeIdentifier(type);
        WTDocument doc = (WTDocument) TypeHelper.newInstance(typeId);
        
        WTContainer product = QueryUtil.getContainerByName(productName);
        
        doc.setName(name);
        doc.setNumber(number);
        doc.setContainer(product);
        
        Folder folder = QueryUtil.getFolder(folderName, WTContainerRef.newWTContainerRef(product));
        if (folder != null) {
            LOGGER.debug("folder exists!");
            FolderHelper.assignLocation(doc, folder);
        }
        
        if(StringUtils.isNotBlank(version)){
        	String[] versionArr = version.split("\\.");
        	if(versionArr.length==2){
        		VersionUtil.setVersion(doc, versionArr[0]);
				VersionUtil.setIteration(doc, versionArr[1]);
        	}else{
        		VersionUtil.setVersion(doc, versionArr[0]);
        	}
        }
        
        doc = (WTDocument) PersistenceHelper.manager.save(doc);
        
        LOGGER.debug("> End createCommonDocumentToFolder");
        return doc;
    }
}
